/* 完整服务器端代码 server.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>

#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024
#define PORT 8080

typedef struct {
    int sockfd;
    struct sockaddr_in addr;
    char nickname[32];
    int active;
} ClientInfo;

ClientInfo clients[MAX_CLIENTS];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void broadcast_message(int sender_fd, const char* message) {
    pthread_mutex_lock(&mutex);
    for (int i = 0; i < MAX_CLIENTS; ++i) {
        if (clients[i].active && clients[i].sockfd != sender_fd) {
            send(clients[i].sockfd, message, strlen(message), 0);
        }
    }
    pthread_mutex_unlock(&mutex);
}

void *client_handler(void *arg) {
    int client_fd = *(int *)arg;
    char buffer[BUFFER_SIZE];
    char nickname[32];
    
    // 获取客户端昵称
    ssize_t bytes = recv(client_fd, nickname, sizeof(nickname)-1, 0);
    if (bytes <= 0) {
        close(client_fd);
        return NULL;
    }
    nickname[bytes] = '\0';

    // 注册新用户
    pthread_mutex_lock(&mutex);
    for (int i = 0; i < MAX_CLIENTS; ++i) {
        if (!clients[i].active) {
            clients[i].sockfd = client_fd;
            clients[i].active = 1;
            strncpy(clients[i].nickname, nickname, sizeof(clients[i].nickname)-1);
            break;
        }
    }
    pthread_mutex_unlock(&mutex);

    // 广播用户加入
    char join_msg[BUFFER_SIZE];
    snprintf(join_msg, sizeof(join_msg), "[系统] %s 加入了聊天室\n", nickname);
    broadcast_message(client_fd, join_msg);

    // 消息处理循环
    while (1) {
        bytes = recv(client_fd, buffer, sizeof(buffer)-1, 0);
        if (bytes <= 0) break;
        buffer[bytes] = '\0';

        // 处理退出命令
        if (strncmp(buffer, "/quit", 5) == 0) break;

        // 构造带昵称的消息
        char formatted_msg[2048];
        snprintf(formatted_msg, sizeof(formatted_msg), "%s: %s", nickname, buffer);
        broadcast_message(client_fd, formatted_msg);
    }

    // 处理用户退出
    pthread_mutex_lock(&mutex);
    for (int i = 0; i < MAX_CLIENTS; ++i) {
        if (clients[i].sockfd == client_fd) {
            clients[i].active = 0;
            break;
        }
    }
    pthread_mutex_unlock(&mutex);

    char leave_msg[BUFFER_SIZE];
    snprintf(leave_msg, sizeof(leave_msg), "[系统] %s 离开了聊天室\n", nickname);
    broadcast_message(client_fd, leave_msg);
    close(client_fd);
    return NULL;
}

int main() {
    int server_fd;
    struct sockaddr_in server_addr;

    // 初始化客户端列表
    for (int i = 0; i < MAX_CLIENTS; ++i) {
        clients[i].active = 0;
    }

    // 创建socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    // 设置端口复用
    int opt = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    // 绑定地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;
    
    if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    // 开始监听
    if (listen(server_fd, 5) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    printf("服务器已启动，监听端口 %d...\n", PORT);

    while (1) {
        struct sockaddr_in client_addr;
        socklen_t addr_len = sizeof(client_addr);
        int client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &addr_len);
        
        if (client_fd < 0) {
            perror("accept");
            continue;
        }

        // 创建线程处理客户端
        pthread_t tid;
        int *pclient = malloc(sizeof(int));
        *pclient = client_fd;
        pthread_create(&tid, NULL, client_handler, pclient);
    }

    close(server_fd);
    return 0;
}